const router = require("koa-router")();
const { createOrder, getOrders } = require("../control/orderControl");
const { SuccessModel, ErrorModel } = require("../messageModel/index");
const loginCheck = require("../middleware/loginCheck");

router.prefix("/api/order");

//创建订单
router.post("/", loginCheck, async (ctx, next) => {
  const requestBody = ctx.request.body;
  const { username } = ctx.session.userInfo;
  const res = await createOrder(username, requestBody);
  try {
    ctx.body = new SuccessModel(res);
  } catch (error) {
    console.error(error);
    ctx.body = new ErrorModel("创建订单失败");
  }
});

//获取订单
router.get("/", loginCheck, async (ctx, next) => {
  const { username } = ctx.session.userInfo;
  const res = await getOrders(username);
  if (res) {
    ctx.body = new SuccessModel(res);
  } else {
    ctx.body = new ErrorModel("未找到该用户订单信息");
  }
});

module.exports = router;
